let ErrorUtils = require('../utils/error/ErrorUtils');
let {User, UserApply, Liuyan} = require('../models');
let lodash = require('lodash');
const {infoLogger, errorLogger} = require('../config').logger;
const Joi = require('joi');
const crypto = require('crypto');
const config = require('../config');
const redis = require('../redis');
let EmailService = require('../service/email');

class AdminVerifyLoginService {
    static async index(content) {
        return content;
    }

    static checkValiData(data) {
        let schema = Joi.object({
            username: Joi.string().min(2).max(30).required(),
            password: Joi.string().min(6).max(16).required()
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     *  用户登录
     * @param data
     * @returns {Promise<void>}
     */
    static async login(data) {
        infoLogger.info('>>>>>>登录开始,请求参数为:', data);
        await AdminVerifyLoginService.checkValiData(data);
        if (!data.username) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_NOT_EXIST);
        }
        let object = {username: "admin", password: "admin123"};
        if (data.username != object.username) {
            ErrorUtils.throwApiError(ErrorUtils.USERNAME_NOT_EXIST);
        }
        // let password = data.password;
        // password = password + config.auth.salt;
        // password.toLowerCase();
        // const md5 = crypto.createHash('md5');
        // md5.update(password);
        // password = md5.digest('hex');
        if (data.password === object.password) {
            //存储用户信息
            await redis.setex(`${config.auth.adminVerifyLoginPrefix}${data.username}`, config.auth.adminTtl, JSON.stringify(object));
            return object;
        } else {
            ErrorUtils.throwApiError(ErrorUtils.PASSWORD_ERROR);
        }
        infoLogger.info(">>>>>>登录结束");
    }

    /**
     * 确认申请
     * @param ctx
     * @returns {Promise<boolean>}
     */
    static async findApplyList(ctx) {

        infoLogger.info('>>>>>:查询后台申请列表开始');
        let list = await UserApply.find()
            .populate({
                select: "name phone username",
                path: "userId"
            })
            .lean()
            .exec();
        infoLogger.info('>>>>>:查询后台申请列表结束');
        return list;
    }

    static checkVerifyValiData(data) {
        let schema = Joi.object({
            applyId: Joi.string().required(),
            status: Joi.string().required(),
            note: Joi.string(),
        });
        let result = Joi.validate(data, schema);
        return result;
    }

    /**
     * 审核信息
     * @param ctx
     * @returns {Promise<*>}
     */
    static async verifyApplyInfo(ctx) {
        let data = ctx.request.body;
        infoLogger.info('>>>>>:查询后台申请列表开始');
        await AdminVerifyLoginService.checkVerifyValiData(data);
        let userApplyInfo = await UserApply.findById(data.applyId).exec();
        if (!userApplyInfo) {
            ErrorUtils.throwApiError(ErrorUtils.APPLY_NOT_EXISTS);
        }
        if (userApplyInfo.status == 2) {
            ErrorUtils.throwApiError(ErrorUtils.VERIFY_SUCCESS_SUCCESS);
        }
        if (userApplyInfo.status == 3) {
            ErrorUtils.throwApiError(ErrorUtils.VERIFY_FAIL);
        }
        if (userApplyInfo.status == 0) {
            ErrorUtils.throwApiError(ErrorUtils.NOT_PAY);
        }
        if (data.status == "pass") {
            await UserApply.update({_id: data.applyId, status: 1},
                {status: 2, verifyTime: new Date()});
        } else {
            infoLogger.info('>>>>>:查询后台申请列表开始',userApplyInfo);
            await Liuyan.create({
                userId: userApplyInfo.userId,
                applyId: userApplyInfo._id,
                addTime: new Date(),
                note: data.note
            });
            await UserApply.update({_id: data.applyId, status: 1},
                {status: 3, verifyTime: new Date()});
        }
        infoLogger.info('>>>>>:查询后台申请列表结束');
        return true;
    }
}

module.exports = AdminVerifyLoginService;
